import 'dart:async';

import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/business/home/widgets/scan_result_widget.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/tools/blue/blue_manger.dart';
import 'package:dmz/tools/blue/blue_tools.dart';

import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import 'package:get/get.dart';
import 'package:gif_view/gif_view.dart';

import 'package:google_mlkit_barcode_scanning/google_mlkit_barcode_scanning.dart';

import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AddBikeController extends BaseController
    with GetSingleTickerProviderStateMixin {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  QRViewController? controller;
  // RxInt animateValue = 1.obs;
  int pageType = 0;
  PageController pageController = PageController();
  Timer? timer;
  int timerNum = 3;
  late AnimationController animationController;
  List<ScanResult> listData = [];
  bool hideBottomNavBar = false;
  int scanType = 0;
  late BuildContext context;
  bool showBottom = false;
  bool contentFinished = false; //连接完成
  String snCoded = '';
  late final GifController gifController;
  bool stoped = false;
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    gifController = GifController(autoPlay: false);
    super.onInit();
    initImages();
  }

  initImages() async {
    var images =
        List.generate(31, (index) => 'assets/images/other/${index + 1}.png');
    for (String frame in images) {
      await precacheImage(AssetImage(frame), Get.context!);
    }
  }

  @override
  void onClose() {
    timer?.cancel();
    gifController.dispose();
    super.onClose();
  }

  ///开始计时
  void startTimer() {
    timer?.cancel();
    // 每隔一秒更新倒计时数字
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timerNum > 0) {
        timerNum--;
        update(['scanResult']);
      } else {
        // 倒计时结束，取消定时器
        timer.cancel();
        Get.back();
        timerNum = 3;
        Get.until((route) => route.settings.name == RouteGet.main);
        Future.delayed(const Duration(seconds: 1), () {
          Get.find<HomePageController>().getVersion(snCoded);
        });
        // Get.until((route) => route.settings.name == RouteGet.main);
      }
    });
  }

  ///结束计时
  void cleanTimer() {
    timerNum = 3;
    timer?.cancel();
  }

  ///二维码扫描
  void onQRViewCreated(QRViewController controllered) {
    controller = controllered;
    controller?.scannedDataStream.listen((scanData) {
      if (scanData.code != null && scanData.code!.contains('SMART-EMC')) {
        controller?.pauseCamera();
        trunScanResult(scanData.code!.split(':').last);
      }
    });
  }

  ///跳转结果页
  trunScanResult(String snCode) {
    Get.toNamed(RouteGet.scanResult, arguments: snCode)?.then((value) {
      controller?.resumeCamera();
    });
  }

  void changePage(int index) {
    if (pageType == index) return;
    pageType = index;
    pageController.jumpToPage(index);
    update();
  }

  ///蓝牙开始扫描
  void blueStarScan() async {
    if (gifController.isPaused) {
      gifController.play();
    }
    var permissions = await FlutterBluePlus.adapterStateNow;
    if (permissions == BluetoothAdapterState.off) {
      scanType = 1;
      if (!showBottom) {
        debugPrint('窗口关闭 ---- 999');
        EMILoding.showBottomWindow(const ScanResultWidget(type: 0), close: () {
          debugPrint('窗口关闭 ---- ');
          showBottom = false;
          gifController.pause();
        });
      }
      return;
    }

    debugPrint("开始扫描");
    EMIBlueMangered().getSanDeviceList((data) {
      listData = data;
      if (listData.isNotEmpty && !showBottom) {
        showBottom = true;
        EMILoding.showBottomWindow(const ScanResultWidget(type: 1), close: () {
          showBottom = false;
          EMIBlueMangered().stopScan();
          gifController.pause();
        });
      } else if (listData.isNotEmpty && showBottom) {
        update(['scanResult']);
      }
    }, finish: (bool have) {
      if (have) return;
      EMILoding.showBottomWindow(const ScanResultWidget(type: 3), close: () {
        showBottom = false;
        gifController.pause();
      });
    });
  }

  ///绑定连接成功
  void contentScuess() {
    startTimer();
    EMILoding.showBottomWindow(const ScanResultWidget(type: 2), close: () {
      showBottom = false;
      cleanTimer();
      Get.back();
    });
  }

  ///请求连接蓝牙
  checkBluetooth(ScanResult data) async {
    await EMIBlueMangered().stopScan();
    var snCode = EMIBlueTool.getSNcode(data);
    RequestClient().post<bool>(APIS.checkBluetooth,
        data: {'sn': snCode}, disLoadCode: 500, onError: (p0) {
      return true;
    }, onResponse: (res) {
      if (res.code == 0 || res.code == 500) {
        didBindBluetooth(snCode, data);
      }
    });
  }

  didBindBluetooth(snCode, ScanResult data) async {
    EMIBlueMangered().stopScan();
    RequestClient().post(APIS.bindBluetooth, data: {'sn_code': snCode},
        onResponse: (res) {
      debugPrint('车辆已绑定 ${data.device.advName}');
      if (res.code == 0 || res.code == 2108) {
        snCoded = snCode;
        contentFinished = true;
        startTimer();
        update(['scanResult']);
        Get.find<HomePageController>().dontGetVison = false;
        Get.find<HomePageController>().getMotolist();

        // EMIBlueMangered().contentCallback(data, snCode, (success) {
        //   if (success) {
        //     EMIBUserManger().snCode = snCode;
        //     //主页面添加设备
        //     Get.find<HomePageController>().getNewMoto(snCode);
        //     contentFinished = true;
        //     debugPrint('连接成功 ${data.device.advName}');
        //   } else {
        //     debugPrint('扫描 连接失败 ${data.device.advName}');
        //   }
        // });
      } else {
        debugPrint('配对失败');
      }
    }, onError: (p0) {
      debugPrint('配对失败');
      return false;
    });
  }

  ///导航栏点击
  Future<void> navigationTopAction() async {
    if (pageType == 0) return Get.toNamed(RouteGet.addProblem);
    List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(maxAssets: 1),
    );
    if (result != null && result.isNotEmpty) {
      var file = await result.first.file;
      final barcodeScanner = BarcodeScanner();
      if (file != null) {
        barcodeScanner.processImage(InputImage.fromFile(file)).then((value) {
          debugPrint('识别结果 -- ${value.first.rawValue}');
          if (value.first.rawValue != null &&
              value.first.rawValue!.contains('SMART-EMC')) {
            controller?.pauseCamera();
            trunScanResult(value.first.rawValue!.split(':').last);
          }
        });
      }
    }
  }
}

class AddBikeBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => AddBikeController());
  }
}
